package org.javaapps.demo.web.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.javaapps.common.web.support.editor.DateEditor;
import org.javaapps.demo.common.Constants;
import org.javaapps.demo.model.UserModel;
import org.javaapps.demo.model.UserQueryModel;
import org.javaapps.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

	@Autowired
	@Qualifier("UserService")
	private UserService userService;

	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public String login(HttpServletRequest request, @ModelAttribute("command") UserQueryModel command, BindingResult result) {
		ValidationUtils.rejectIfEmptyOrWhitespace(result, "username", "notempty", "用户名不能为空");
		ValidationUtils.rejectIfEmptyOrWhitespace(result, "password", "notempty", "密码不能为空");
		if (!request.getSession().getAttribute("validateImg").toString().equalsIgnoreCase(command.getValidateImg())) {
			result.rejectValue("error", "validateImg", "验证码输入错误！");
		}
		
		if (result.hasErrors()) {
			return "login";
		}
		UserModel model = userService.getUser(command);
		List<UserModel> m2List = userService.listeq(UserModel.class, command, -1, -1);
		if (m2List.size() > 0)
			System.out.println(m2List.get(0));
		if (model != null) {
			request.getSession().setAttribute(Constants.SESSION_USER, model);
			return "redirect:main.jsp";
		}
		result.rejectValue("error", "notempty", "用户名和密码输入不正确！");
		return "login";
	}
	
	@RequestMapping(value = "/login", method = { RequestMethod.GET })
	public String login(){
		return "login";
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DateEditor());
	}
}
